package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.bean.MyTrackBean;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.MyRecordTrackAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.databinding.ActivityRecordTrackListBinding;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

public class RecordTrackListActivity extends MyBaseActivity<ActivityRecordTrackListBinding> {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private MyRecordTrackAdapter myRecordTrackAdapter;
    private String userId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_record_track_list;
    }

    @Override
    protected void initView() {


    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
         binding.recyclerView.setLayoutManager(manager1);
         binding.recyclerView.addItemDecoration(new TopSpaceItemDecoration());
         binding.recyclerView.addItemDecoration(new BottomSpaceItemDecoration());

        myRecordTrackAdapter = new MyRecordTrackAdapter();
        if (isOpenLoadAnimation) {
            myRecordTrackAdapter.isFirstOnly(isFirstOnly);
            myRecordTrackAdapter.openLoadAnimation(animationType);
        }

        myRecordTrackAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recyclerView.setAdapter(myRecordTrackAdapter);
        myRecordTrackAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String trackId = myRecordTrackAdapter.getData().get(position).getId();
                Bundle bundle = new Bundle();
                bundle.putString("trackId", trackId);
                IntentUtils.getInstance().readyGo(RecordTrackListActivity.this, TrackDetailsActivity.class, bundle);
            }

        });

        String name = getIntent().getStringExtra("name");
        userId = getIntent().getStringExtra("userId");
        if (!StringUtils.isEmpty(name)) {
            setModuleTitle(name + "的巡护记录");
        } else {
            setModuleTitle("巡护记录");
        }

        initListener();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void getData() {
        if (!StringUtils.isEmpty(userId)) {
            peopleTrackInfo(1);
        } else {
            ToastUtils.showLong("数据获取失败！");
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //当用户处在次页面的时候，联网之后刷新数据
        String message = event.getMessgae();
        if (message.equals(Constant.REFRESH_MY_TRACK_DATA)) {
            try {
                peopleTrackInfo(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                 binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                 binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                peopleTrackInfo(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(myRecordTrackAdapter.getData(), Constant.PAGE_SIZE);
                    peopleTrackInfo(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 员工轨迹
     */
    private void peopleTrackInfo(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("userId", userId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_PATROL_PEOPLE_TASK)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            MyTrackBean myTrackBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                myTrackBean = new MyTrackBean();
                                myTrackBean = gson.fromJson(result, MyTrackBean.class);

                                List<MyTrackBean.PageBean.ListBean> dataBeans = myTrackBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;

                                        if (dataBeans != null && dataBeans.size() > 0) {
                                            for (int i = 0; i < dataBeans.size(); i++) {
                                                MyTrackBean.PageBean.ListBean listBean = dataBeans.get(i);
                                                listBean.setIsUpload(true);
                                            }
                                        }

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            myRecordTrackAdapter.replaceData(dataBeans);
                                        } else {
                                            myRecordTrackAdapter.addData(dataBeans);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }
}